<?php

namespace App\Modules\Apicrzs\Entities;

use App\Models\Model;
use App\Modules\Admin\Entities\Member\UserBankModel;
use App\Modules\Admin\Entities\Member\UsersIdCardModel;
use App\Modules\Admin\Entities\Member\WaterCardModel;
use App\Traits\Instance;
use App\Traits\MysqlTable;
use Illuminate\Database\Eloquent\Builder;

class UsersModel extends Model
{
    use Instance;
    use MysqlTable;
    protected $table='users';

    protected $is_delete = 0; //是否开启删除（1.开启删除，就是直接删除；0.假删除）
    protected $hidden = ['password', 'salt','pw'];

    protected $guarded = [];
    public function getIsDelete()
    {
        return $this->is_delete;
    }


    public function usersIdCard()
    {
        return $this->hasOne(UsersIdCardModel::class, 'user_id','id');
    }
    public function usersBark()
    {
        return $this->hasOne(UserBankModel ::class, 'user_id','id');
    }

    /**
     * 模型的 "booted" 方法
     *
     * 应用全局作用域
     *
     * @return void
     */
    protected static function booted()
    {
        // 假删除的作用域
        $static = new static;
        static::addGlobalScope('delete', function(Builder $builder) use ($static){
            if ($static->is_delete == 0) $builder->where($static->delete_field, $static->is_delete);
        });
    }

    public function getAdminByName(string $admin_name)
    {
        return $this->where('account', $admin_name)->first();
    }

    public function setPasswordAttribute($key)
    {
        if (empty($key)) unset($this->attributes['password']);
//        else $this->attributes['password'] = hash_encryption($key);
        else $this->attributes['password'] = $key;
    }


    public function user_info($user_id)
    {
        return $this->where(['id'=>$user_id])->first();
    }
    public function user_info_by_openid($openid)
    {
        return $this->where(['openid'=>$openid])->first();
    }
    public function user_info_by_uniqid($uniqid)
    {
        return $this->where(['uniqid'=>$uniqid])->first();
    }


    public function waterCards()
    {
        return $this->hasOne(WaterCardModel::class,'user_id','id');
    }

}
